<?php

class SupermodController extends ControllerBase
{
	private $_model;

	public function init() {
		Util::app()->theme = ADMIN_THEME;
		parent::init();
		$this->registerFancybox();
 	}

	public function registerFancybox(){
		//Add calendar
		Util::registerScriptFile(Util::themeUrl().'/js/jquery-ui-1.10.3.custom.min.js');
		Util::registerScriptFile(Util::themeUrl().'/js/custome.datepicker.js');
		Util::registerCssFile(Util::themeUrl().'/css/ui-smoothness.datepick.css','screen');

		// Add mousewheel plugin (this is optional)
		Util::registerScriptFile(Util::themeUrl() . '/js/fancybox/jquery.mousewheel-3.0.6.pack.js', CClientScript::POS_HEAD);

		// Add fancyBox main JS and CSS files
		Util::registerScriptFile(Util::themeUrl() . '/js/fancybox/jquery.fancybox.js?v=2.0.6');
		Util::registerCssFile(Util::themeUrl().'/js/fancybox/jquery.fancybox.css?v=2.0.6','screen');

		if (isset($_GET['ajax']))
		$this->layout = '//layouts/none';
	}


	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return CMap::mergeArray(parent::filters(),array(
			'accessControl', // perform access control for CRUD operations
		));
	}
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'users'=>Util::getAdmins(),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	/**
	 * Manages all models.
	 */
	public function actionIndex()
	{
		$model=new SuperMod('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['SuperMod']))
            $model->attributes=$_GET['SuperMod'];

        $this->render('index',array(
            'model'=>$model,
        ));
	}
	/**
	 * Update_status
	 */
	public function actionUpdate_status($id, $returnUrl) {
		$model = $this->loadModel($id);
		$model->status = ($model->status == 1) ? 0 : 1;
		$model->superuser = 2;
		$model->update('status');

		if (!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array($returnUrl));
		exit;
	}

	/**
	 * Displays a particular model.
	 */
	public function actionView()
	{
		$model = $this->loadModel();
		$this->render('view',array(
			'model'=>$model,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model		= new SuperMod;
		$profile	= new Profile;

		$model->status 		= STATUS_ACTIVE;
		$profile->regMode 	= true;

		if(isset($_POST['SuperMod']))
		{
			$model->attributes		= $_POST['SuperMod'];
			$model->activkey		= UserModule::encrypting(microtime().$model->password);
			$model->superuser		= SUPERMOD;
			$profile->attributes	= $_POST['Profile'];
			$profile->user_id		= 0;

			// Connvert string to lowercase
			$profile->fullname		= Util::formatFullName($profile->fullname, true);
			// Clear all character non numberic
			$inputPhone				= $profile->phone;
			$inputCellPhone			= $profile->cellphone;
			$inputListCourse		= $_POST['Profile']['listcourses'];
			$profile->phone			= Util::formatPhone($inputPhone, false);
			$profile->cellphone		= Util::formatPhone($inputCellPhone, false);
			$profile->listcourses	= json_encode($inputListCourse);

			if($model->validate()&& $profile->validate()) {
				$model->verifyPassword 	= $model->password	= UserModule::encrypting($model->password);
				if (isset($_FILES['Profile']['size']['avatar']) && $_FILES['Profile']['size']['avatar'] > 0) {
					$avatar 				= CUploadedFile::getInstance($profile, 'avatar');
					$tmpNm				= time()-1;
                	$imageName 			= strtolower($tmpNm . "." . $avatar->getExtensionName());
                	$profile->avatar	= $imageName;
                	$avatar->saveAs(Util::pathUpload('avatar') .'/' . $imageName);
				}
				if($model->save()) {
					$profile->user_id=$model->id;
					if ($profile->save()) {
						$arrUrl = array('view','id'=>$model->id);
						if (isset($_GET['ajax'])) {
							$arrUrl['ajax'] = true;
						}
						$this->redirect($arrUrl);
					}
				}


			}else $profile->validate();

			$profile->fullname 		= Util::formatFullName($profile->fullname);
			$profile->phone			= $inputPhone;
			$profile->cellphone		= $inputCellPhone;
			$profile->listcourses	= $inputListCourse;
		}

		$this->render('create',compact('model', 'profile'));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate()
	{
		$model		= $this->loadModel();
		$profile	= $model->profile;
		$profile->listcourses = json_decode($profile->listcourses, true);

		if(isset($_POST['SuperMod']))
		{
			$model->attributes		= $_POST['SuperMod'];
			$profile->attributes	= $_POST['Profile'];

			// Connvert string to lowercase
			$profile->fullname		= Util::formatFullName($profile->fullname, true);
			// Clear all character non numberic
			$inputPhone				= $profile->phone;
			$inputCellPhone			= $profile->cellphone;
			$profile->phone			= Util::formatPhone($inputPhone, false);
			$profile->cellphone		= Util::formatPhone($inputCellPhone, false);
			$inputListCourse		= $_POST['Profile']['listcourses'];
			$profile->listcourses	= json_encode($inputListCourse);

			if($model->validate()&& $profile->validate()) {
				$oldModel = User::model()->notsafe()->findByPk($model->id);
				if ($oldModel->password != $model->password) {
					$model->password=Yii::app()->controller->module->encrypting($model->password);
					$model->activkey=Yii::app()->controller->module->encrypting(microtime().$model->password);
				}

				if (isset($_FILES['Profile'])) {
					$oldAvatar	= $oldModel->profile->avatar;
					if (isset($_FILES['Profile']['size']['avatar']) && $_FILES['Profile']['size']['avatar'] > 0) {
						$avatar 			= CUploadedFile::getInstance($profile, 'avatar');
						$tmpNm				= time()-1;
	                	$imageName 			= strtolower($tmpNm . "." . $avatar->getExtensionName());
	                	$profile->avatar	= $imageName;
	                	$avatar->saveAs(Util::pathUpload('avatar') .'/' . $imageName);


						if (($oldAvatar != '') && file_exists(Util::pathUpload('slide') .'/' . $oldAvatar)) {
	                		unlink(Util::pathUpload('avatar') .'/' . $oldAvatar);
	                	}
					}
					else {
						$profile->avatar 	= $oldAvatar;
					}
	            }
	            if ($model->save()) {
	            	if ($profile->save()) {
						$arrUrl = array('view','id'=>$model->id);
						if (isset($_GET['ajax'])) {
							$arrUrl['ajax'] = true;
						}
						$this->redirect($arrUrl);
	            	}
	            }

			}else $profile->validate();

			$profile->fullname 	= Util::formatFullName($profile->fullname);
			$profile->phone		= $inputPhone;
			$profile->cellphone	= $inputCellPhone;
			$profile->listcourses = $inputListCourse;
		}

		$this->render('update',compact('model', 'profile'));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			$ids 		= $_POST['chk'];
			$username 	= "";
			if (is_array($ids)) {
				foreach ($ids as $key){
					$profile 	= Profile::model()->findByPk($key);
					if (isset($profile)) {
						$username	= $profile->user->username;
						$profile->delete();
					}
					SuperMod::model()->deleteByPk($key);
				}
			}

			$this->setFlash("Dữ liệu đã được xóa.");
			if (isset($_GET['ajax'])) {
				$this->printFlash();
				exit;
			} else {
				$this->redirect(array('/user/supermod'));
			}
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($validate)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
        {
            echo CActiveForm::validate($validate);
            Yii::app()->end();
        }
    }


	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=SuperMod::model()->notsafe()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

}